<script setup>
import { h, onMounted, ref, resolveDirective, withDirectives } from 'vue'
import { VueDraggableNext } from 'vue-draggable-next';
import {
  NForm,
  NFormItem,
  NInput,
  NInputNumber,
  NFlex, NButton,
  NImage, NUpload,
  useMessage, NAvatar,
} from 'naive-ui'
import default_image from "@/assets/images/mz.jpg"
import CommonPage from '@/components/page/CommonPage.vue'
import { getToken } from '@/utils'
import { useCRUD } from '@/composables'
import api from '@/api'
import {useRoute} from "vue-router"
import {router} from "@/router";
import {useTagsStore} from "@/store";
import TheIcon from "@/components/icon/TheIcon.vue";
const tagsStore = useTagsStore()
const route = useRoute()

defineOptions({ name: '专题页编辑' })

const $table = ref(null)
const queryItems = ref({})
const message = useMessage()
const vPermission = resolveDirective('permission')
const base_path = import.meta.env.VITE_BASE

const {
  modalVisible,
  modalTitle,
  modalLoading,
  modalForm,
  modalFormRef,
  handleEdit,
  handleDelete,
  handleAdd,
  handleSave,
} = useCRUD({
  name: '专题页编辑',
  initForm: {},
  doCreate: api.createMiniTopic,
  doUpdate: api.updateMiniTopic,
  doDelete: api.deleteMiniTopic,
  refresh: () => $table.value?.handlerefresh(),
})

const data = reactive({
  uploadAction: base_path + 'api/mini/topic/file',
  token: getToken(),
  row:[],
  fileList:[],
  id:0,
  show_edit:0,
  all:0,
  contact_goods:[],
  contact_goods_options:[]
})
const data2 = reactive({
  select_id:0,
})
const handleFinish = ({ file, event }) => {
  let data = (event?.target).response
  data = JSON.parse(data)
  if (data.code === 200) {
    modalForm.value.content.forEach((item) => {
      if(item.id === data2.select_id){
        item["url"] = data.data.url
      }
    })
    message.success('上传成功')
  } else {
    message.error(data.data)
  }

  return file
}

onMounted(() => {
  const id = route.query.id
  modalVisible.value = true
  if(id>0){
    get_data(id)
  }else{
    handleAdd()
    modalForm.value.content = []
  }
  api.getallgoods().then((res) => (data.contact_goods_options = res.data))
  $table.value?.handleSearch()
})
watch(modalVisible, (newValue, oldValue) => {
  if(!modalVisible.value){
    tagsStore.removeTag(route.fullPath)
    router.push("/mini/mini_settings/topic")
  }
});

async function get_data(id) {
  let ret =await api.getMiniTopicById({data_id:id})
  data.row = ret.data
  data.all = 1
  handleEdit(data.row)
}
function on_list(){
  tagsStore.removeTag(route.fullPath)
  router.push("/mini/mini_settings/topic")
}
function on_save(){
  handleSave()
}
function add_layout(type){
  let item = null
  if(type===1){
    item = {
      id:get_maxid(modalForm.value.content),
      type:type,
      url:default_image
    }
  }
  if(type===2){
    item = {
      id:get_maxid(modalForm.value.content),
      type:type,
      goods:[{
        value:0,
        label:"点击修改商品",
        cover:default_image,
        price:"0~0"
      }]
    }
  }
  modalForm.value.content.push(item)
  data.all++
}
function del_layout(id){
  let index = 0
  modalForm.value.content.forEach((item) => {
    if(item.id === id){
      modalForm.value.content.splice(index, 1);
      data.show_edit = 0
    }
    index++
  })
  data.all--
}
function get_maxid(data){
  let id = 0
  if(!data){
    return id+1
  }
  data.forEach((item) => {
    if(item["id"]>=id){
      id = item["id"]
    }
  })
  return id+1
}
function edit_image(item){
  data.show_edit = item.type
  data2.select_id = item.id
  if(item.url!==default_image){
    data.fileList = [{
      id:1,
      name:'封面',
      url:item.url,
      status:"finished"
    }]
  }

}
function edit_goods(item){
  data.show_edit = item.type
  data2.select_id = item.id
  data.contact_goods = get_goods_id(item.goods)
}
function update_goods(value){
  let goods = []
  value.forEach((item) => {
    let g =get_gooditem(item)
    goods.push(g)
  })
  modalForm.value.content.forEach((item) => {
    if(item.id === data2.select_id){
      item["goods"] = goods
    }
  })
}
function get_gooditem(id){
  let good = {}
  data.contact_goods_options.forEach((item) => {
    if(item.value === id){
      good = item
    }
  })
  return good
}
function get_goods_id(data){
  let ids = []
  data.forEach((item) => {
    if(item.value>0){
      ids.push(item.value)
    }

  })
  return ids
}

const validate = {
    name: [
        {
            required: true,
            message: '请输入名称',
            trigger: ['input', 'blur', 'change'],
        },
    ],
}
</script>

<template >
  <!-- 业务页面 -->
  <CommonPage show-footer title="专题页编辑" >
    <template #action>
      <div>
        <NButton  class="float-right mr-15" type="primary"
                  @click="on_list">
          <TheIcon icon="material-symbols:info" :size="18" class="mr-5"/>
          返回列表页
        </NButton>
        <NButton  class="float-right mr-15" type="primary"
                  @click="on_save">
          <TheIcon icon="material-symbols:save" :size="18" class="mr-5"/>
          保存
        </NButton>
      </div>
    </template>

    <NForm
        ref="modalFormRef"
        label-placement="left"
        label-align="left"
        :label-width="80"
        :model="modalForm"
        :rules="validate"
    >

      <n-grid x-gap="12"  :y-gap="0" :cols="10">
        <n-gi  :span="2">
          <n-card title="基础属性" embedded >
            <NFormItem  path="name" style="width: 100%">
              <NInput v-model:value="modalForm.name" clearable placeholder="专题名称" />
            </NFormItem>
          </n-card>
          <n-card title="选择组件" embedded style="margin-top: 10px">
            <n-space>
              <n-button type="primary" dashed @click="add_layout(1)">图片组件</n-button>
              <n-button type="primary" dashed @click="add_layout(2)">商品组件</n-button>
            </n-space>
          </n-card>
        </n-gi>
        <n-gi  :span="3"  >
          <n-card  embedded content-style="padding:20px 0;">
            <n-scrollbar style="max-height: 800px;padding: 0 20px" class="image-container">
              <div v-show="data.all===0">
                <n-empty description="请先添加组件"> </n-empty>
              </div>

              <VueDraggableNext v-model="modalForm.content" item-key="id">
                <div  v-for="item in modalForm.content" class="image-container draggable" style="position: relative">
                  <n-image width="100%" :class="item.id===data2.select_id?'active':''" v-if="item.type===1" :src="item.url" preview-disabled  class="custom-image" @click="edit_image(item)"/>
                  <div v-if="item.type===2" :class="item.id===data2.select_id?'active':''">
                    <n-card class="goods_item" v-for="item2 in item.goods"  @click="edit_goods(item)">
                      <n-flex  justify="space-around">
                        <n-image width="100" :fallback-src="default_image" height="100" :src="item2.cover" preview-disabled  class="custom-image"/>
                        <n-flex vertical justify="space-around" style="width: 200px">
                          <n-ellipsis :line-clamp="2">{{item2.label}}</n-ellipsis>
                          <div>{{item2.price}}</div>
                          <n-button type="primary" size="small">立即购买</n-button>
                        </n-flex>
                      </n-flex>
                    </n-card>

                  </div>
                  <n-tag type="primary"  :bordered="false" style="position: absolute;left:2px;top:2px;color: white;background: #8945c3">组件{{item.id}}</n-tag>
                </div>
              </VueDraggableNext>
            </n-scrollbar>
          </n-card>
        </n-gi>
        <n-gi  :span="5">
          <n-card :title="'图片组件'+data2.select_id+'属性'" embedded v-if="data.show_edit===1">

            <n-upload
                :max="1"
                :action="data.uploadAction"
                :headers="{ token: data.token }"
                list-type="image-card"
                @finish="handleFinish"
                v-if="data.show_edit===1"
                v-model:file-list="data.fileList"
            >
              点击上传
            </n-upload>

            <n-button type="primary" style="margin-top: 10px;width: 96px;" @click="del_layout(data2.select_id)">
              删除组件
            </n-button>

          </n-card>

          <n-card :title="'商品组件'+data2.select_id+'属性'" embedded v-if="data.show_edit===2">
            <n-transfer
                v-model:value="data.contact_goods"
                :options="data.contact_goods_options"
                source-filterable
                :on-update-value="update_goods"
            />

            <n-button type="primary" style="margin-top: 10px;width: 96px;" @click="del_layout(data2.select_id)">
              删除组件
            </n-button>



          </n-card>
        </n-gi>
      </n-grid>

    </NForm>
  </CommonPage>
</template>

<style>
.custom-image {
  margin: 0; /* 去掉外边距 */
  padding: 0; /* 去掉内边距 */
}
.active{
  border:2px dashed red;
}
.image-container {
  display: flex;
  flex-direction: column;
  gap: 0; /* 设置间隙为 0 */
  cursor: grab;
}
.goods_item{
  margin-bottom: 10px;
}
</style>